<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统日志</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background: linear-gradient(180deg, #fff8e1 0%, #e8f5e9 100%);
            min-height: 100vh;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: rgba(255, 255, 255, 0.9);
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
        }
        .navbar {
            background-color: rgba(51, 51, 51, 0.95);
            overflow: hidden;
            margin-bottom: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        .navbar a {
            float: left;
            display: block;
            color: white;
            text-align: center;
            padding: 14px 16px;
            text-decoration: none;
            transition: all 0.3s;
        }
        .navbar a:hover {
            background-color: rgba(221, 221, 221, 0.9);
            color: black;
        }
        .navbar a.active {
            background-color: #4CAF50;
        }
        h1 {
            color: #333;
            margin-bottom: 30px;
            text-align: left;
        }
        .header-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-bottom: 20px;
        }
        .header-actions button {
            margin-left: 10px;
            padding: 8px 12px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .header-actions button:hover {
            background-color: #45a049;
        }
        .header-actions button:last-child {
            background-color: #f44336;
        }
        .header-actions button:last-child:hover {
            background-color: #d32f2f;
        }
        .last-refresh {
            margin-bottom: 20px;
            font-size: 0.8em;
            color: #555;
        }
        .filter-row {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            align-items: center;
        }
        .filter-row select, .filter-row input {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            min-width: 120px;
        }
        .filter-row button {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .filter-row button:hover {
            background-color: #45a049;
        }
        .log-filter {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 20px;
            padding: 15px;
            background-color: #f9f9f9;
            border-radius: 5px;
        }
        .log-filter select, .log-filter input {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .log-filter button {
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .log-filter button:hover {
            background-color: #45a049;
        }
        .log-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        .log-table th, .log-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        .log-table th {
            background-color: #f2f2f2;
            position: sticky;
            top: 0;
        }
        .log-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .log-table tr:hover {
            background-color: #f1f1f1;
        }
        .log-level {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 12px;
            font-weight: bold;
        }
        .log-level.debug {
            background-color: #17a2b8;
            color: white;
        }
        .log-level.info {
            background-color: #28a745;
            color: white;
        }
        .log-level.warn {
            background-color: #ffc107;
            color: black;
        }
        .log-level.error, .log-level.fatal {
            background-color: #dc3545;
            color: white;
        }
        .log-type {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 12px;
            font-weight: bold;
            margin-right: 5px;
        }
        .log-type.system {
            background-color: #007bff;
            color: white;
        }
        .log-type.operation {
            background-color: #6f42c1;
            color: white;
        }
        .log-type.network {
            background-color: #fd7e14;
            color: white;
        }
        .log-type.other {
            background-color: #20c997;
            color: white;
        }
        .log-type.error {
            background-color: #dc3545;
            color: white;
        }
        .pagination {
            display: flex;
            justify-content: center;
            gap: 5px;
            margin-top: 20px;
        }
        .pagination button {
            padding: 5px 10px;
            border: 1px solid #ddd;
            background-color: #fff;
            cursor: pointer;
            border-radius: 3px;
        }
        .pagination button.active {
            background-color: #4CAF50;
            color: white;
            border-color: #4CAF50;
        }
        .pagination button:hover:not(.active) {
            background-color: #f1f1f1;
        }
        .pagination button:disabled {
            color: #ccc;
            cursor: not-allowed;
        }
        .view-details {
            padding: 3px 8px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        .view-details:hover {
            background-color: #0069d9;
        }
        .refresh-info {
            font-size: 12px;
            color: #666;
            margin-top: 10px;
        }
        
        /* 模态框样式 */
        .modal {
            display: block;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            overflow: auto;
        }
        
        .modal-content {
            background-color: #fefefe;
            margin: 10% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 800px;
            border-radius: 5px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }
        
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }
        
        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
        }
        
        .log-details {
            margin-top: 15px;
            line-height: 1.6;
        }
        
        .log-details h4 {
            margin-top: 15px;
            border-bottom: 1px solid #eee;
            padding-bottom: 5px;
        }
        
        /* 消息提示样式 */
        .message {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 4px;
            color: white;
            z-index: 1001;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
            animation: slide-in 0.3s ease-out;
        }
        
        .message.success {
            background-color: #28a745;
        }
        
        .message.error {
            background-color: #dc3545;
        }
        
        .message.info {
            background-color: #17a2b8;
        }
        
        .message.warning {
            background-color: #ffc107;
            color: #333;
        }
        
        .message.fade-out {
            animation: fade-out 0.5s ease-out forwards;
        }
        
        @keyframes slide-in {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
        
        @keyframes fade-out {
            from { opacity: 1; }
            to { opacity: 0; }
        }
    </style>
</head>
<body>
    <div class="navbar">
        <a href="/welcome.html">首页</a>
        <a href="/monitor.html">监控</a>
        <a href="/config.html" id="configLink" style="display: none;">配置</a>
        <a href="/log.html" class="active">日志</a>
        <a href="/music.html">音乐</a>
    </div>
    
    <div class="container">
        <h1>系统日志</h1>
        
        <div class="last-refresh">
            最近刷新时间: <span id="lastRefreshTime">-</span>
        </div>
        
        <div class="header-actions">
            <button onclick="refreshLogs()">刷新日志</button>
            <button onclick="downloadLogs()">下载日志</button>
            <button onclick="logout()">退出登录</button>
        </div>
        
        <div id="message"></div>
        
        <div class="filter-row">
            <select id="log-type" onchange="changeLogType(this.value)">
                <option value="system">系统日志</option>
                <option value="operation">操作日志</option>
                <option value="network">网络日志</option>
                <option value="other">其他日志</option>
                <option value="error">错误日志</option>
            </select>
            
            <select id="log-level">
                <option value="all">所有级别</option>
                <option value="DEBUG">调试</option>
                <option value="INFO">信息</option>
                <option value="WARN">警告</option>
                <option value="ERROR">错误</option>
                <option value="FATAL">致命</option>
            </select>
            
            <select id="log-service">
                <option value="all">所有服务</option>
                <option value="web_server">Web服务</option>
                <option value="monitor_server">监控服务</option>
                <option value="config_server">配置服务</option>
                <option value="bluetooth_server">蓝牙服务</option>
                <option value="cloud_server">云对接服务</option>
            </select>
            
            <input type="text" id="log-search" placeholder="搜索关键词">
            <input type="date" id="log-date">
            <button onclick="filterLogs()">筛选</button>
        </div>
        
        <!-- 日志内容区域 -->
        <div id="log-content">
            <table class="log-table" id="log-table">
                <thead>
                    <tr id="table-header">
                        <th>时间</th>
                        <th>级别</th>
                        <th>类型</th>
                        <th>服务</th>
                        <th>消息</th>
                        <th>详情</th>
                    </tr>
                </thead>
                <tbody id="log-table-body">
                    <tr>
                        <td colspan="6" class="text-center">加载中...</td>
                    </tr>
                </tbody>
            </table>
            
            <div class="pagination" id="log-pagination">
                <!-- 分页控件将通过JavaScript动态生成 -->
            </div>
        </div>
    </div>
    
    <script>
        // 当前选中的日志类型
        let currentLogType = 'system';
        // 当前页码
        let currentPage = 1;
        
        // 页面加载时检查用户信息
        document.addEventListener('DOMContentLoaded', function() {
            const username = localStorage.getItem('username');
            const userRole = localStorage.getItem('userRole');
            
            if (!username || !userRole) {
                window.location.href = '/login.html';
                return;
            }
            
            // 根据用户角色显示/隐藏配置入口
            if (userRole === 'admin') {
                document.getElementById('configLink').style.display = 'block';
            }

            // 设置当前活动页面的样式
            const currentPath = window.location.pathname;
            document.querySelectorAll('.navbar a').forEach(link => {
                if (link.getAttribute('href') === currentPath) {
                    link.classList.add('active');
                } else {
                    link.classList.remove('active');
                }
            });

            // 设置日期选择器为今天
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('log-date').value = today;
            
            // 加载日志
            refreshLogs();
        });
        
        // 更改日志类型
        function changeLogType(type) {
            currentLogType = type;
            currentPage = 1;
            showMessage('已选择' + getLogTypeName(currentLogType) + '，请点击"刷新日志"按钮加载数据', 'info');
        }
        
        // 获取日志类型名称
        function getLogTypeName(type) {
            const typeNames = {
                'system': '系统日志',
                'operation': '操作日志',
                'network': '网络日志',
                'other': '其他日志',
                'error': '错误日志'
            };
            return typeNames[type] || type;
        }
        
        // 筛选日志
        function filterLogs() {
            // 重置页码
            currentPage = 1;
            
            // 刷新日志
            refreshLogs();
        }
        
        // 刷新日志
        function refreshLogs() {
            // 获取筛选参数
            const level = document.getElementById('log-level').value;
            const service = document.getElementById('log-service').value;
            const search = document.getElementById('log-search').value;
            const dateElement = document.getElementById('log-date');
            const date = dateElement && dateElement.value ? dateElement.value : '';
            
            // 显示加载中
            const tableBody = document.getElementById('log-table-body');
            tableBody.innerHTML = '<tr><td colspan="6" class="text-center">加载中...</td></tr>';
            
            // 构建请求参数
            const params = {
                level: level,
                service: service,
                search: search,
                date: date,
                page: currentPage,
                page_size: 20
            };
            
            // 确定要请求的日志类型
            const requestType = currentLogType;
            console.log(`加载${requestType}日志，参数:`, params);
            
            // 调用API
            fetch(`/api/logs/${requestType}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(params)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    // 更新表格
                    updateLogTable(data);
                    
                    // 更新分页
                    updatePagination(data);
                    
                    // 更新刷新时间
                    const now = new Date();
                    const formattedTime = now.toLocaleString();
                    document.getElementById('lastRefreshTime').textContent = formattedTime;
                    
                    showMessage('日志已刷新', 'success');
                })
                .catch(error => {
                    console.error('获取日志失败:', error);
                    tableBody.innerHTML = `<tr><td colspan="6" class="text-center">获取日志失败: ${error.message}</td></tr>`;
                    showMessage(`获取日志失败: ${error.message}`, 'error');
                });
        }
        
        // 更新日志表格
        function updateLogTable(data) {
            const tableBody = document.getElementById('log-table-body');
            
            // 清空表格
            tableBody.innerHTML = '';
            
            // 如果没有日志
            if (!data.logs || data.logs.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="6" class="text-center">没有找到符合条件的日志</td></tr>';
                return;
            }
            
            // 添加日志行
            data.logs.forEach(log => {
                const row = document.createElement('tr');
                
                // 创建时间单元格
                const timeCell = document.createElement('td');
                timeCell.textContent = log.time;
                row.appendChild(timeCell);
                
                // 创建级别单元格
                const levelCell = document.createElement('td');
                const levelSpan = document.createElement('span');
                levelSpan.className = `log-level ${log.level.toLowerCase()}`;
                levelSpan.textContent = log.level;
                levelCell.appendChild(levelSpan);
                row.appendChild(levelCell);
                
                // 创建类型单元格
                const typeCell = document.createElement('td');
                const typeSpan = document.createElement('span');
                // 根据日志类型设置样式
                const logType = log.category || currentLogType;
                typeSpan.className = `log-type ${logType}`;
                typeSpan.textContent = getLogTypeName(logType);
                typeCell.appendChild(typeSpan);
                row.appendChild(typeCell);
                
                // 创建服务单元格
                const serviceCell = document.createElement('td');
                serviceCell.textContent = log.service || '-';
                row.appendChild(serviceCell);
                
                // 创建消息单元格
                const messageCell = document.createElement('td');
                messageCell.textContent = log.message;
                row.appendChild(messageCell);
                
                // 创建详情单元格
                const detailsCell = document.createElement('td');
                const detailsButton = document.createElement('button');
                detailsButton.className = 'view-details';
                detailsButton.textContent = '查看';
                detailsButton.onclick = function() {
                    viewLogDetails(log);
                };
                detailsCell.appendChild(detailsButton);
                row.appendChild(detailsCell);
                
                tableBody.appendChild(row);
            });
        }
        
        // 更新分页
        function updatePagination(data) {
            const pagination = document.getElementById('log-pagination');
            
            // 清空分页
            pagination.innerHTML = '';
            
            // 如果只有一页，不显示分页
            if (data.pages <= 1) {
                return;
            }
            
            // 添加上一页按钮
            const prevButton = document.createElement('button');
            prevButton.innerHTML = '&lt;&lt;';
            prevButton.disabled = data.page <= 1;
            prevButton.onclick = () => changePage(data.page - 1);
            pagination.appendChild(prevButton);
            
            // 添加页码按钮
            const startPage = Math.max(1, data.page - 2);
            const endPage = Math.min(data.pages, startPage + 4);
            
            for (let i = startPage; i <= endPage; i++) {
                const pageButton = document.createElement('button');
                pageButton.textContent = i;
                pageButton.classList.toggle('active', i === data.page);
                pageButton.onclick = () => changePage(i);
                pagination.appendChild(pageButton);
            }
            
            // 添加下一页按钮
            const nextButton = document.createElement('button');
            nextButton.innerHTML = '&gt;&gt;';
            nextButton.disabled = data.page >= data.pages;
            nextButton.onclick = () => changePage(data.page + 1);
            pagination.appendChild(nextButton);
        }
        
        // 切换页码
        function changePage(page) {
            currentPage = page;
            refreshLogs();
        }
        
        // 查看日志详情
        function viewLogDetails(log) {
            // 创建模态框
            const modal = document.createElement('div');
            modal.className = 'modal';
            
            // 格式化详情
            let detailsHtml = '';
            if (log.details) {
                for (const [key, value] of Object.entries(log.details)) {
                    detailsHtml += `<div><strong>${key}:</strong> ${JSON.stringify(value)}</div>`;
                }
            }
            
            // 设置模态框内容
            modal.innerHTML = `
                <div class="modal-content">
                    <span class="close" onclick="this.parentElement.parentElement.remove()">&times;</span>
                    <h3>日志详情</h3>
                    <div class="log-details">
                        <div><strong>时间:</strong> ${log.time}</div>
                        <div><strong>级别:</strong> <span class="log-level ${log.level.toLowerCase()}">${log.level}</span></div>
                        <div><strong>类型:</strong> <span class="log-type ${log.category || currentLogType}">${getLogTypeName(log.category || currentLogType)}</span></div>
                        <div><strong>服务:</strong> ${log.service || '-'}</div>
                        <div><strong>消息:</strong> ${log.message}</div>
                        <div><strong>来源:</strong> ${log.source || '-'}</div>
                        <h4>详细信息</h4>
                        ${detailsHtml || '<div>无详细信息</div>'}
                    </div>
                </div>
            `;
            
            // 添加到页面
            document.body.appendChild(modal);
            
            // 点击模态框外部关闭
            modal.onclick = function(event) {
                if (event.target === modal) {
                    modal.remove();
                }
            };
        }
        
        // 显示消息
        function showMessage(message, type = 'info') {
            const messageBox = document.createElement('div');
            messageBox.className = `message ${type}`;
            messageBox.textContent = message;
            
            document.body.appendChild(messageBox);
            
            // 3秒后自动消失
            setTimeout(() => {
                messageBox.classList.add('fade-out');
                setTimeout(() => {
                    messageBox.remove();
                }, 500);
            }, 3000);
        }
        
        // 下载日志
        function downloadLogs() {
            // 获取筛选参数
            const level = document.getElementById('log-level').value;
            const service = document.getElementById('log-service').value;
            const search = document.getElementById('log-search').value;
            const dateElement = document.getElementById('log-date');
            const date = dateElement && dateElement.value ? dateElement.value : '';
            
            // 显示下载中消息
            showMessage('正在准备下载...', 'info');
            
            // 构建请求参数
            const params = {
                level: level,
                service: service,
                search: search,
                date: date,
                page: 1,
                page_size: 1000
            };
            
            // 确定要请求的日志类型，调用API获取日志
            const requestType = currentLogType;
            fetch(`/api/logs/${requestType}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(params)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    if (!data.logs || data.logs.length === 0) {
                        showMessage('没有找到符合条件的日志', 'warning');
                        return;
                    }
                    
                    // 将日志转换为CSV格式
                    let csvContent = '';
                    
                    // 添加CSV头
                    csvContent = '时间,级别,类型,服务,消息\n';
                    
                    // 添加数据行
                    data.logs.forEach(log => {
                        const logType = log.category || currentLogType;
                        csvContent += `"${log.time}","${log.level}","${getLogTypeName(logType)}","${log.service || ''}","${log.message.replace(/"/g, '""')}"\n`;
                    });
                    
                    // 创建Blob对象
                    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                    
                    // 创建下载链接
                    const link = document.createElement('a');
                    const url = URL.createObjectURL(blob);
                    
                    // 设置下载属性
                    link.setAttribute('href', url);
                    link.setAttribute('download', `${requestType}_logs_${new Date().toISOString().split('T')[0]}.csv`);
                    link.style.visibility = 'hidden';
                    
                    // 添加到页面并触发点击
                    document.body.appendChild(link);
                    link.click();
                    
                    // 清理
                    document.body.removeChild(link);
                    URL.revokeObjectURL(url);
                    
                    showMessage('日志下载成功', 'success');
                })
                .catch(error => {
                    console.error('下载日志失败:', error);
                    showMessage(`下载日志失败: ${error.message}`, 'error');
                });
        }
        
        // 退出登录
        async function logout() {
            try {
                const response = await fetch('/api/logout', {
                    method: 'POST'
                });
                
                if (response.ok) {
                    window.location.href = '/login.html';
                } else {
                    showMessage('退出失败: ' + (await response.text()), 'error');
                }
            } catch (error) {
                showMessage('退出失败: ' + error.message, 'error');
            }
        }
    </script>
</body>
</html>
